package com.mobile.web.auth;

import java.util.HashMap;
import java.util.Map;

import com.mobile.service.dto.AuthDTO;
import com.mobile.service.dto.AuthQueryDTO;
import com.mobile.service.entity.Auth;
import com.mobile.util.*;
import com.mobile.util.config.aop.AutoFill;
import com.mobile.util.config.aop.OperateType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.mobile.service.inter.system.AuthService;
import com.mobile.web.base.BaseController;
import com.mobile.web.config.util.Jurisdiction;

import javax.validation.Valid;

/**
 * 权限管理API接口
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "权限管理接口", description = "包含权限的查询、新增、修改、删除等操作")
public class AuthController extends BaseController {

    @Autowired
    private AuthService authService;

    /**
     * 新增权限信息
     *
     * @return
     */
    @PostMapping("/addAuth")
    //@RequiresPermissions("authmana:add:1")
    @Operation(
            summary = "创建权限",
            description = "新增权限信息，权限名称和编码为必填项"
    )
    @AutoFill(OperateType.INSERT)
    public Object addAuth(@Valid AuthDTO authDTO) {
        PageData pd = this.getPageData();
        Map<String, Object> map = null;

        // 保存权限信息
        try {
            map = authService.addAuth(authDTO);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(pd, map);
    }

    /**
     * 权限信息列表
     *
     * @return
     */
    @RequestMapping(value = "/getAuthListPage")
    //@RequiresPermissions("authmana:read:1")
    @Operation(
            summary = "分页查询权限",
            description = "根据条件分页查询权限列表，支持模糊查询权限名称"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功，返回分页数据"),
            @ApiResponse(responseCode = "400", description = "参数错误（如页码小于1）"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Object getAuthListPage(@Validated AuthQueryDTO authQueryDTO) {
        Map<String, Object> map = new HashMap<>();
        try {
            PageResult<AuthDTO> authPage = authService.getAuthListPage(authQueryDTO);
            map.put("page", authPage);
            map.put("data", authPage.getPageDatas());
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        // 按钮权限
        map.put("QX", Jurisdiction.getHC(this.getUserCode(),"authmana"));
        return AppUtil.returnObject(map);
    }

    /**
     * 根据id获取权限信息
     *
     * @return
     */
    @PostMapping(value = "/getAuthById")
    //@RequiresPermissions("authmana:edit:1")
    @Operation(
            summary = "查询权限详情",
            description = "根据权限ID查询完整信息，包含关联的角色信息"
    )
    public Object getAuthById( @Parameter(description = "权限ID", required = true, example = "1001")
                                   @RequestParam("authId") Integer authId) {
        Map<String, Object> map = new HashMap<>();
        try {
            AuthDTO auth = authService.getAuthById(authId);
            if (StringUtil.isEmpty(auth)) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
                return map;
            }
            map.put("data", auth);
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(map);
    }


    /**
     * 修改权限信息
     *
     * @return
     */
    @RequestMapping("/updateAuth")
    //@RequiresPermissions("authmana:edit:1")
    @Operation(
            summary = "编辑权限",
            description = "编辑权限，权限名称和编码为必填项"
    )
    @AutoFill(OperateType.UPDATE)
    public Object updateAuth(@Valid  AuthDTO authDTO) {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<>();

        try {
            map = authService.updateAuth(authDTO);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(pd, map);
    }

    /**
     * 根据id删除权限
     *
     * @return
     */
    @RequestMapping("/removeAuth")
    //@RequiresPermissions("authmana:delete:1")
    public Object removeAuth(@RequestParam("authId") Integer authId) {
        Map<String, Object> map;

        try {
            map = authService.removeAuth(authId);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(map);
    }
}
